<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="/api/upload"
          :headers="{ 'Authorization': `Bearer ${getToken()}` }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" :disabled="!!formData.id" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="昵称" prop="systemUserName">
        <el-input v-model="formData.systemUserName" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="请选择角色" style="width: 100%">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.roleName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio value="1">启用</el-radio>
          <el-radio value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="display: inline-block; margin-right: 10px;">
        <p style="color: red; font-size: 12px;line-height: 1.5;">* 重置密码后，原密码将失效，请谨慎操作！</p>
        <p style="color: red; font-size: 12px;line-height: 1.5;">* 默认密码为：123456789，请及时修改密码！</p>
      </div>

      <el-button v-if="formData.id" type="danger" @click="resetPasswordFn(formData.id)">重置密码</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import http from '@/utils/request.js';
import { ElMessage, ElMessageBox } from 'element-plus'
import { resetPassword } from '@/api/systemUser'

const props = defineProps({
  dialogTitle: String,
  formData: Object,
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue', 'submit'])

const dialogVisible = ref(false)
const formRef = ref(null)
const roleOptions = ref([])
// 获取角色列表
http.get('/role/getAll').then(res => {
    roleOptions.value = res.data
})

const resetPasswordFn = (id) => {
   ElMessageBox.confirm(
    '你确定重置密码吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger',
    }
    ).then(() => {
      resetPassword({id}).then(res => {
        ElMessage.success('重置密码成功')
      }).catch(err => {
        ElMessage.error('重置密码失败')
      })
    })
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  systemUserName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
    console.log(response, URL.createObjectURL(file.raw))
    props.formData.avatar = response.data
  }

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }

  return isImage && isLt2M
}

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

// 监听dialogVisible变化
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    formRef.value?.resetFields()
  }
})

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    emit('submit', props.formData)
    dialogVisible.value = false
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
}
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: border-color 0.3s;
}
.avatar-uploader-icon:hover {
  border-color: #409eff;
}
</style>
